//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/sever.js');
var network = require('../../utils/network.js');
Page({
  data: {
    userInfo: "",
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imgUrls: [],
    // indicatorDots: false,
    interval: 5000,
    duration: 1000,
    autoplay: false,
    indicatordots: true,
    circular: true,
    indicatoractivecolor: "#ffffff",
    token: "",
    latitude: "",
    longitude: "",
    location: "",
    shopList: [],
    isadders: "",
    myUserCode: "",
    region: ['重庆市', '重庆市', '南岸区'],
    bannerOk: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
      if (!res.hasUpdate) {
        var mypageTow = util.myToken("mypageTow")
        console.log(mypageTow)
        if (mypageTow) {
          util.setToken("mypageTow", "")
          wx.navigateTo({
            url: mypageTow + ""
          })
        }
      }
    })

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function() {
      // 新版本下载失败
    })

    _this.setData({
      myUserCode: options.user_code
    })
    wx.login({
      success: function(res) {
        var mycode = ""
        if (_this.data.myUserCode) {
          mycode = _this.data.myUserCode
        }
        var data = {
          code: res.code,
          user_code: mycode
        }
        _this.mycode(data);
      }
    });
  },
  onShow: function() {
    var _this = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // console.log(res)
              // 可以将 res 发送给后台解码出 unionId
              console.log(res.userInfo)
              _this.setData({
                userInfo: res.userInfo
              })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (_this.userInfoReadyCallback) {
                _this.userInfoReadyCallback(res)
              }
            }
          })
        } else {
          wx.redirectTo({
            url: '../authorization/authorization'
          })
        }
      }
    })
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          var data = {
            is_location: "0"
          }
          _this.shopList(data)
          _this.setData({
            isadders: false
          })
        }
      }
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: util.title,
      path: 'pages/index/index',
      imageUrl: util.imageUrl,
      success: function(res) {

      },
      fail: function(res) {

      }
    }
  },
  //交换token
  mycode: function(data) {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/getWeChatInfo", data, '正在加载数据', "", function(res) {

      util.setToken("myToken", res.data.token_type + " " + res.data.access_token)
      var mytoen = util.myToken("mypage")
      if (mytoen) {
        util.setToken("mypage", "")
        wx.navigateTo({
          url: mytoen + ""
        })
      }
      // util.setToken("myToken", res.data.token_type + " " + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3J4c2ouY3FmdXl1YW4uY24vYXBpL3Rlc3QvZ2V0VXNlclRva2VuIiwiaWF0IjoxNTQwMDEwODg4LCJleHAiOjE1NDAwMTQ0ODgsIm5iZiI6MTU0MDAxMDg4OCwianRpIjoiVHd3dm40djU2TFloRzNQTSIsInN1YiI6MTkwMywicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.FRBKNDLMKVpyD6PRxATd4oWJEaEBEO1yCNTxInB0jGM")
      // if (res.data.is_info == 0) {
      var data = {
        nickname: _this.data.userInfo.nickName ? _this.data.userInfo.nickName : "",
        image: _this.data.userInfo.avatarUrl ? _this.data.userInfo.avatarUrl : ""
      }
      _this.homeBanner()
      _this.location()
      _this.upUser(data)
    }, function() {
      wx.showToast({
        icon: "none",
        title: '加载数据失败',
      })
    })

  },
  //完善信息
  upUser: function(data) {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/user/saveUserInfo", data, '', util.myToken("myToken"), function(res) {

    }, function() {
      wx.showToast({
        icon: "none",
        title: '加载数据失败',
      })
    })
  },
  //我的位置
  location: function() {
    var _this = this;
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        // console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        var data = {
          jd: res.longitude,
          wd: res.latitude
        }
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          is_location: "1"
        })
        _this.setData({
          isadders: true
        })
        _this.locationTow(latitude, longitude)
        _this.shopList(data)
      }
    })
  },
  locationTow: function(latitude, longitude) {
    var _this = this;
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo?parameters&location=' + longitude + ',' + latitude + '&key=3820619eeedbf4c400a8b61c264d4669', //仅为示例，并非真实的接口地址
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        // console.log(res.data.regeocode)
        _this.setData({
          location: res.data.regeocode.addressComponent.province + ">" + res.data.regeocode.addressComponent.district
        })
        // location
      }
    })
  },
  //首页banner
  homeBanner: function() {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/index/banners", "", '', util.myToken("myToken"), function(res) {
      _this.setData({
        imgUrls: res.data,
      })
    }, function() {
      wx.showToast({
        icon: "none",
        title: '加载数据失败',
      })
    })
  },
  //店铺列表
  shopList: function(data) {
    var _this = this;
    network.requestLoading(util.getRequestUrl + "/api/index/shops", data, '', util.myToken("myToken"), function(res) {
      _this.setData({
        shopList: res.data
      })
    }, function() {
      wx.showToast({
        icon: "none",
        title: '加载数据失败',
      })
    })
  },
  //导航
  navigation: function(e) {
    var mynav = e.currentTarget.dataset
    // console.log(mynav)
    wx.openLocation({
      latitude: Number(mynav.latitude),
      longitude: Number(mynav.longitude),
      name: mynav.name,
      scale: 18,
    })
  },
  //详情
  details: function(e) {
    var myid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../shopdetails/shopdetails?id=' + myid
    })
  },
  //评论
  pinglun: function(e) {
    var myid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../shopdetails/shopdetails?id=' + myid
    })
  },
  //点赞
  dianzan: function(e) {
    var _this = this;
    var myid = e.currentTarget.dataset.id;
    var data = {
      id: myid
    }
    network.requestLoading(util.getRequestUrl + "/api/user/praise", data, '', util.myToken("myToken"), function(res) {
      wx.showToast({
        icon: "none",
        title: '点赞成功',
      })
      _this.location()
    }, function() {
      wx.showToast({
        icon: "none",
        title: '加载数据失败',
      })
    })
  },
  //区域选择
  bindRegionChange: function(e) {
    var _this = this;
    _this.setData({
      location: e.detail.value[0] + ">" + e.detail.value[2]
    })
    wx.request({
      url: 'https://restapi.amap.com/v3/config/district?key=3820619eeedbf4c400a8b61c264d4669&keywords=' + e.detail.value[2] + '&subdistrict=0&extensions=base',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        console.log(res)
        var myadcode = ''
        for (var i = 0; i < res.data.districts.length; i++) {
          if (myadcode == '') {
            myadcode = res.data.districts[i].adcode
          } else {
            myadcode = myadcode + "," + res.data.districts[i].adcode
          }
        }
        if (_this.data.longitude) {
          var data = {
            is_location: 1,
            jd: _this.data.longitude,
            wd: _this.data.latitude,
            adcode: myadcode
          }
        } else {
          var data = {
            is_location: 0,
            adcode: myadcode
          }
        }

        _this.shopList(data)
      }
    })
  },
  //banner是否加载完成
  bannerload: function() {
    var _this = this;
    var mybannerOk = _this.data.bannerOk + 1;
    var myLenhth = _this.data.imgUrls.length;
    if (mybannerOk == myLenhth) {
      _this.setData({
        bannerOk: mybannerOk,
        autoplay: true
      })
      console.log("完成")
    } else {
      _this.setData({
        bannerOk: mybannerOk,
      })
      console.log("未完成")
    }

  }

})